class Solution {

    Set<Integer> t = new HashSet<>();
    int n;

    public Set<Integer> dfs(int u, Set<Integer> s, int[][] graph) {
        if (t.contains(u)) {
            return Collections.emptySet();
        }
        s.add(u);
        for (int v = 0; v < n; v++) {
            if (graph[u][v] == 0 || s.contains(v)) {
                continue;
            }
            Set<Integer> ns = dfs(v, s, graph);
            if (ns.isEmpty()) {
                return Collections.emptySet();
            }
            s.addAll(ns);
        }
        return s;
    }

    public int minMalwareSpread(int[][] graph, int[] initial) {
        for (int v : initial) {
            t.add(v);
        }
        n = graph.length;
        Arrays.sort(initial);
        int ans = -1, mx = 0;
        for (int u : initial) {
            Set<Integer> vis = new HashSet<>();
            vis.add(u);
            for (int v = 0; v < n; v++) {
                if (graph[u][v] == 0 || vis.contains(v)) {
                    continue;
                }
                Set<Integer> s = new HashSet<>();
                s.add(u);
                vis.addAll(dfs(v, s, graph));
            }
            int cur = vis.size();
            if (cur > mx) {
                mx = cur;
                ans = u;
            }
        }
        return ans;
    }
}